package com.dabbo.starship.player;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.dabbo.starship.interfaces.Player;
import com.dabbo.starship.interfaces.PlayerPoolInterface;

public class PlayerPool extends java.rmi.server.UnicastRemoteObject implements PlayerPoolInterface {

	private static final long serialVersionUID = -6398848187105227051L;

	protected HashMap<Integer, Player> playerPool;
	
	public PlayerPool() throws RemoteException {
		playerPool = new HashMap<Integer, Player>();
	}
	
	@Override
	public HashMap<Integer, Player> getPlayerPool() throws RemoteException {
		return this.playerPool;
	}

	@Override
	public void setPlayerPool(HashMap<Integer, Player> playerPool) throws RemoteException {
		this.playerPool = playerPool;
	}

	@Override
	public int getTotalActivePlayers() throws RemoteException {
		int count = 0;
		Set<Entry<Integer, Player>> set = playerPool.entrySet(); 
		Iterator<Entry<Integer, Player>> i = set.iterator(); 
		while(i.hasNext()) { 
			Map.Entry<Integer, Player> ent = (Map.Entry<Integer, Player>) i.next();
			Player plr = (PlayerUnit) ent.getValue();
			if (plr.getActiveStatus()) {
				count++;
			}
		}
		return count;
	}

	@Override
	public Player logonPlayer(String username, String password) throws RemoteException {
		System.out.println("loginPlayer(" + username + ", " + password + ") called");
		System.out.println("    PlayerPool size = " + playerPool.size()); 			
		Set<Entry<Integer, Player>> set = playerPool.entrySet(); 
		Iterator<Entry<Integer, Player>> i = set.iterator(); 
		while(i.hasNext()) { 
			Map.Entry<Integer, Player> ent = (Map.Entry<Integer, Player>) i.next();
			PlayerUnit plr = (PlayerUnit) ent.getValue();
			System.out.println("    : (e) " + plr.getUsername()); 			
			if (plr.getUsername().equalsIgnoreCase(username)) {
				System.out.println("    ^ Found existing user, retrieving details"); 			
				return plr;
			}
		}
		PlayerUnit pl = new PlayerUnit(username);
		pl.setActiveStatus(true);
		pl.setCommandCode("");
		pl.setCredits(10000);
		pl.setHealth(100);
		pl.setPlayerName("Dabbo");
		playerPool.put(pl.hashCode(), pl);
		System.out.println("    Unable to locate user, Adding new user."); 			
		return pl;
	}
	

}
